<template>
  <div style="width:100%;padding:0;margin: 0;">
    <!--        显示题目内容和编辑框-->
    <el-card   v-for="(item,id) in arr" shadow="never" :key="item.id"
               style="margin: 0;"
               :draggable="ifIsDraggable(item.isEditing)"
    >

      <!--        单选-->
      <template v-if="item.type=='dan'" >
        <single-choice :item="item" :id="id" :auto-id="showId"
                       @editMe="editMe(item)"
                       @moveUp="moveUp(id)"  @moveUpUp="moveUpUp(id)"  @moveDown="moveDown(id)"  @moveDownDown="moveDownDown(id)"
                       @copyMe="copyMe(item,id)" @deleteMe="deleteMe(item,id)"
        ></single-choice>
      </template>

      <!--        多选-->
      <template v-else-if="item.type=='mul'" >
        <mul-choice :item="item" :id="id" :auto-id="showId"
                    @editMe="editMe(item)"
                    @moveUp="moveUp(id)"  @moveUpUp="moveUpUp(id)"  @moveDown="moveDown(id)"  @moveDownDown="moveDownDown(id)"
                    @copyMe="copyMe(item,id)" @deleteMe="deleteMe(item,id)"
        ></mul-choice>
      </template>

      <!--        填空-->
      <template v-else-if="item.type=='tk'">
        <single-tiankong
            :item="item" :id="id" :auto-id="showId"
            @editMe="editMe(item)"
            @moveUp="moveUp(id)"  @moveUpUp="moveUpUp(id)"  @moveDown="moveDown(id)" @moveDownDown="moveDownDown(id)"
            @copyMe="copyMe(item,id)" @deleteMe="deleteMe(item,id)"
        ></single-tiankong>
      </template>

      <!--        评分-->
      <template v-else-if="item.type=='rate'">
        <rate-slider
            :item="item" :id="id" :showId="showId" :auto-id="showId"
            @editMe="editMe(item)"
            @moveUp="moveUp(id)"  @moveUpUp="moveUpUp(id)"  @moveDown="moveDown(id)"
            @moveDownDown="moveDownDown(id)"
            @copyMe="copyMe(item,id)" @deleteMe="deleteMe(item,id)"
        ></rate-slider>
      </template>

    </el-card>

    <!--      添加题目-->
    <el-card shadow="never"  v-if="isAdding" style="margin:0 auto;padding:20px 30px 0px 30px;text-align: left;">

      <!--        添加单选-->
      <div v-if="addType=='dan'">
        <el-form v-model="addDanObj" >
          <add-question-head
              :thisquestion="addDanObj"
          ></add-question-head>
          <el-form-item  v-for="(option,opindex) in addDanObj.options" :key="option.id" style="width:90%;margin: 3px auto;">
            <span style="font-size:16px;line-height: 1.3;">选项{{opindex+1}}：</span>
            <el-input  style="width: 70%;" v-model="option.val" :value="option.val"  :disabled=ifDisable(option) type="textarea" :autosize="{ minRows: 1}"></el-input>
            <el-button circle style="margin-left: 5px;" :icon="editOrSaveOptionIcon(option)" @click.prevent="editItemOption(opindex,addDanObj)" ></el-button>
            <el-button circle style="margin-left: 5px;" icon="el-icon-delete" @click.prevent="removeItemOption(opindex,addDanObj)" ></el-button>
            <el-button circle style="margin-left: 5px;" icon="el-icon-plus" @click.prevent="addItemOptionAfterMe(opindex,addDanObj)" ></el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--        添加多选-->
      <div v-else-if="addType=='mul'">
        <el-form v-model="addMulObj" >
          <add-question-head
              :thisquestion="addMulObj"
          ></add-question-head>

          <el-form-item style="width:90%;margin: 3px auto;" v-for="(option,opindex) in addMulObj.options" :key="opindex" >
            <span style="font-size:16px;line-height: 1.3;">选项{{opindex+1}}：</span>
            <el-input  style="width: 70%;" v-model="option.val" :value="option.val"  :disabled=ifDisable(option) type="textarea" :autosize="{ minRows: 1}"></el-input>
            <el-button circle style="margin-left: 5px;" :icon="editOrSaveOptionIcon(option)" @click.prevent="editItemOption(opindex,addMulObj)" ></el-button>
            <el-button circle style="margin-left: 5px;" icon="el-icon-delete" @click.prevent="removeItemOption(opindex,addMulObj)" ></el-button>
            <el-button circle style="margin-left: 5px;" icon="el-icon-plus" @click.prevent="addItemOptionAfterMe(opindex,addMulObj)" ></el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--        添加填空-->
      <div v-else-if="addType=='tk'">
        <el-form v-model="addTkObj"  >
          <add-question-head
              :thisquestion="addTkObj"
          ></add-question-head>
        </el-form>
      </div>


      <div v-else-if="addType=='rate'">
        <el-form v-model="addRateObj"  >
          <add-question-head
              :thisquestion="addRateObj"
          ></add-question-head>
        </el-form>
      </div>


      <!--        两个按钮-->
      <el-button-group  style="margin: 3px auto;position:relative;left:34%" >
        <el-button size="mini" icon="el-icon-check" @click="SaveAddition()">保存本题</el-button>
        <el-button  size="mini"  icon="el-icon-close" @click="notSave()">取消本题</el-button>
      </el-button-group>

    </el-card>
  </div>

</template>
<script>
import SingleChoice from "@/components/EditQuestionnaire/SingleChoice";
import MulChoice from "@/components/EditQuestionnaire/MulChoice";
import SingleTiankong from "@/components/EditQuestionnaire/SingleTiankong";
import RateSlider from "@/components/EditQuestionnaire/RateSlider";
import AddQuestionHead from "@/components/EditQuestionnaire/AddQuestionHead";
import {
  confirmQuestionnaireOrder,
  questionnaireAddQuestion,
  questionCreateNonSelection,
  questionCreateSelection,
  questionEditTitle,
  questionEditRemark,
  questionEditOptional, questionCopyQuestion, questionDelQuestion,
  questionCreateOption,
  questionDeleteOption,
  questionEditOptionDescription,
  questionEditOptionRemark, questionnaireSetIsOrder, GetAllQuestionInfo,
  questionnaireChangeQuestionnaireTitle,
} from "../api";
export default {
  name:'editbody',
  components:{
    SingleChoice,MulChoice,SingleTiankong,RateSlider,AddQuestionHead
  },
  props:{
    showId:Boolean,
    wenjuanTitle:String,
  },
  data(){
    return {
      IniShowId:null,
      arr: [],
      isAdding:false,
      addType:null,
      isShow:true,
      addDanObj:{
        id:null,
        isEditing:true,
        bidati:false,
        type:'dan',
        title:'',
        note:'',
        options: [],
        radio:null,
      },
      addMulObj:{
        id:null,
        bidati:false,
        isEditing:true,
        type:'mul',
        title:'',
        note:'',
        options: [],
        checked:[],
      },
      addTkObj:{
        id:null,
        bidati:false,
        isEditing:true,
        type:'tk',
        title:'',
        note:'',
        text:'',
      },
      addRateObj:{
        id:null,
        bidati:false,
        isEditing: true,
        type:'rate',
        title:'',
        note:'',
        val:0,
      },
    }
  },
  computed:{
    ifIsDraggable(){
      return function (op){
        if(op)return false;
        else return true;
      }
    },
    ifShadow(){
      return function (item){
        return (item.isEditing)? "never": "always";
      }
    },
    editOrSaveIcon(){
      return function (item){
        return (item.isEditing)?"el-icon-finished":"el-icon-edit";
      }
    },
    editOrSaveWords(){
      return function (item){
        return (item.isEditing)?"保存":"编辑";
      }
    },
    editOrSaveOptionIcon(){
      return function (option){
        return (option.notEditing)?"el-icon-edit":"el-icon-finished";
      }
    },
    ifDisable(){
      return function (option){
        return (option.notEditing)? true: false;
      }
    }

  },

  mounted(){
    this.IniThisWenJuan();
  },

  watch:{
    arr:{
      handler:function (newVal){
        var dl=[];
        for(var i in newVal){
          dl.push(newVal[i].title);
        }
        this.$emit('changedagang',dl);
      },
      deep:true
    }
  },
  methods:{

    // 获取本问卷所有题目(包含选项)
    IniThisWenJuan:function (){
      GetAllQuestionInfo(this.$store.state.uid,this.$route.query.questionnaireId).then(res=>{
        console.log(res);
        if(res.error_code==0){
          this.$emit('setqqshowid',res.is_order);
          this.$emit('shownairtitle',res.questionnaire_title);

          console.log(res);
          this.showId=res.is_order;

          this.arr=[];
          for(var i in res.question_list){
            var tt= {}
            tt.id=res.question_list[i].id;
            tt.bidati=!res.question_list[i].optional;
            tt.order=res.question_list[i].order;
            tt.note=res.question_list[i].remark;
            tt.title=res.question_list[i].title;
            switch(res.question_list[i].type){
              case 'S':tt.type='dan';tt.radio=null;break;
              case 'M':tt.type='mul';tt.checked=[];break;
              case 'F':tt.type='tk';tt.text="";break;
              case 'R':tt.type='rate';tt.val="";break;
            }

            if(res.question_list[i].type=="M"||res.question_list[i].type=="S"){
              tt.options=[];
              for(var j in res.question_list[i].option){
                var opop= {}
                opop.id=res.question_list[i].option[j].id;
                opop.remark=res.question_list[i].option[j].remark;
                opop.val=res.question_list[i].option[j].description;
                tt.options.push(opop);
              }
            }
            this.arr.push(tt);
          }
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e)})
    },

    // 编辑选项的按钮组函数
    editItemOption:function (opindex,item){
      if(item.options[opindex].notEditing){
        item.options[opindex].notEditing=false;
      }else{
        item.options[opindex].notEditing=true;
        this.ReqEditItemOptionDesc(item.options[opindex]);
        this.ReqEditItemOptionRemark(item.options[opindex]);
      }
    },

    ReqEditItemOptionDesc:function (theOp){
      questionEditOptionDescription(this.$store.state.uid,theOp.id,theOp.val).then(res=>{
        if(res.error_code==0){
          console.log("修改选项内容成功");
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e)})
    },
    ReqEditItemOptionRemark:function (theOp){
      questionEditOptionRemark( this.$store.state.uid,theOp.id,theOp.val).then(res=>{
        if(res.error_code==0){
          console.log("修改选项备注成功");
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e)})
    },

    removeItemOption:function (opindex,item){
      var tmp=Object.values({...item.options});
      var theOp=tmp[opindex];
      questionDeleteOption(this.$store.state.uid,item.id,theOp.id).then(res=>{
        if(res.error_code==0){
          console.log("要删除的选项");
          console.log(theOp);
          tmp.splice(opindex,1);
          item.options=tmp;
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e)})
    },
    addItemOptionAfterMe:function (opindex,item){
      var x={};
      x.val='选项';x.remark='';x.notEditing=false;
      questionCreateOption(this.$store.state.uid,item.id,opindex+1,x.val,x.remark).then(res=>{
        if(res.error_code==0){
          var tmp=Object.values({...item.options});
          x.id=res.option_id;
          tmp.splice(opindex+1,0,x);
          item.options=tmp;
          console.log(item.options);
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e)})
    },

    //提交整张问卷，提交题目id的array+是否显示题号+问卷标题
    FinishEditAndSaveSort:function (){
      var quesSort=[];
      for(var i in this.arr){
        quesSort.push(this.arr[i].id);
      }
      console.log(quesSort);
      confirmQuestionnaireOrder(this.$store.state.uid,this.$route.query.questionnaireId,quesSort).then(res=>{
        if(res.error_code==0){
          console.log("成功提交题目顺序");
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e);})

      questionnaireSetIsOrder(this.$store.state.uid,this.$route.query.questionnaireId,this.showId).then(res=>{
        if(res.error_code==0){
          console.log("成功提交是否显示题号");
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e);})

      questionnaireChangeQuestionnaireTitle(this.$store.state.uid,this.$route.query.questionnaireId,this.wenjuanTitle).then(res=>{

        console.log(this.wenjuanTitle);

        if(res.error_code==0){
          console.log("成功提交问卷标题");
        }else{
          console.log(res);
        }
      }).catch(e=>{console.log(e);})

    },

    // 无数据请求的编辑题目按钮组
    moveUp:function (id){
      if(id==0)return;
      const a=this.arr.slice(id,id+1);
      const b=this.arr.slice(id-1,id);
      this.arr.splice(id-1,2,a[0],b[0]);
    },
    moveUpUp:function (id){
      if(id==0)return;
      const a=this.arr.slice(id,id+1);
      this.arr.splice(id,1);
      this.arr.unshift(a[0]);
    },
    moveDown:function (id){
      if(id==this.arr.length-1)return;
      const a=this.arr.slice(id,id+1);
      const b=this.arr.slice(id+1,id+2);
      this.arr.splice(id,2,b[0],a[0]);
    },
    moveDownDown:function(id){
      if(id==this.arr.length-1)return;
      const a=this.arr.slice(id,id+1);
      this.arr.splice(id,1);
      this.arr.push(a[0]);
    },


    // 有数据请求的编辑单个题目按钮组
    editMe:function (item) {
      if(item.isEditing){
        item.isEditing=false;
        console.log(item);
        this.Save(item);
      }else{
        item.isEditing=true;
      }
    },
    copyMe:function (item,id){
      questionCopyQuestion(this.$store.state.uid,item.id).then(res=>{
        if(res.error_code==0){
          var q=Object.create(null);
          q={...q};
          q.id=res.question_id;
          q.isEditing=item.isEditing;
          q.title=item.title;
          q.note=item.note;
          q.type=item.type;
          switch (item.type){
            case 'dan':
              var qops=[];
              for(var i in item.options){
                var vv={};
                vv.val=item.options[i].val;
                vv.remark=item.options[i].remark;
                vv.notEditing=true;
                qops.push(vv);
              }
              q.options=qops;
              q.radio=null;
              break;
            case 'mul':
              var aqops=[];
              for(var ai in item.options){
                var avv={};
                avv.val=item.options[ai].val;
                avv.remark=item.options[ai].remark;
                avv.notEditing=true;
                aqops.push(avv);
              }
              q.options=aqops;
              q.checked=[];
              break;
            case 'tk':
              q.text='';
              break;
            case 'rate':
              q.val=0;
              break;
          }

          console.log(q);
          this.arr.splice(id+1,0,q);
          console.log(this.arr);
        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
    },
    deleteMe:function (item,id){
      this.arr.splice(id,1);
      this.ReqDelete(item);

      // if(this.ReqDelete(item)){
      //   this.arr.splice(id,1);
      // }
    },
    ReqDelete:function (item){
      questionDelQuestion(this.$store.state.uid,this.$route.query.questionnaireId,item.id).then(res=>{
        if(res.error_code==0){
          console.log("删除成功：",this.$route.query.questionnaireId,item.id);
          return true;
        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
      return false;
    },
    ReqAddToNair:function (nid){
      console.log(this.$store.state.uid);
      console.log(this.$route.query.questionnaireId);
      console.log(nid);
      questionnaireAddQuestion(this.$store.state.uid,this.$route.query.questionnaireId,nid).then(res=>{
        if(res.error_code==0){
          console.log("添加题目成功",this.$route.query.questionnaireId,nid);
        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
    },
    addDan:function (){
      if(this.isAdding){
        this.SaveAddition();
      }
      this.isAdding=true;
      this.addType='dan';
      this.addDanObj.isEditing=true;
      this.addDanObj.title='单选题标题';
      this.addDanObj.note='';
      var r={};
      r.val='选项';r.notEditing=false;r.remark='';
      this.addDanObj.options=[];
      this.addDanObj.options.push(r);
      this.addDanObj.radio=null;

      var optional=!this.addDanObj.bidati;
      questionCreateSelection(this.$store.state.uid,this.addDanObj.title,'S',optional,this.addDanObj.note).then(res=>{
        if(res.error_code==0){
          this.addDanObj.id=res.question_id;
          console.log(this.addDanObj.id);

          // 把题目添加进问卷
          this.ReqAddToNair(res.question_id);

          // 默认新建一个选项
          questionCreateOption(this.$store.state.uid,this.addDanObj.id,0,this.addDanObj.options[0].val,this.addDanObj.options[0].remark).then(res=>{
            if(res.error_code==0){
              this.addDanObj.options[0].id=res.option_id;
              console.log(this.addDanObj.options);
            }else{
              console.log(res);
            }
          }).catch(e=>{console.log(e)})

        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
    },
    addMul:function (){
      if(this.isAdding){
        this.SaveAddition();
      }
      this.isAdding=true;
      this.addType='mul';
      this.addMulObj.isEditing=true;
      this.addMulObj.title='多选题标题';
      this.addMulObj.note='';
      this.addMulObj.options=[];
      var r={};
      r.val='选项';r.notEditing=false;r.remark='';
      this.addMulObj.options.push(r);
      this.addMulObj.checked=[];

      var optional=!this.addMulObj.bidati;
      questionCreateSelection(this.$store.state.uid,this.addMulObj.title,'M',optional,this.addMulObj.note).then(res=>{
        if(res.error_code==0){
          this.addMulObj.id=res.question_id;
          console.log(this.addMulObj.id);

          // 把题目添加进问卷
          this.ReqAddToNair(res.question_id);

          // 默认新建一个选项
          questionCreateOption(this.$store.state.uid,this.addMulObj.id,0,this.addMulObj.options[0].val,this.addMulObj.options[0].remark).then(res=>{
            if(res.error_code==0){
              this.addMulObj.options[0].id=res.option_id;
              console.log(this.addMulObj.options);
            }else{
              console.log(res);
            }
          }).catch(e=>{console.log(e)})


        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
      return -1;
    },
    addTk:function (){
      if(this.isAdding){
        this.SaveAddition();
      }
      this.isAdding=true;
      this.addType='tk';
      this.addTkObj.isEditing=true;
      this.addTkObj.title='单项填空标题';
      this.addTkObj.note='';
      this.addTkObj.text='';

      var optional=!this.addTkObj.bidati;
      questionCreateNonSelection(this.$store.state.uid,this.addTkObj.title,'F',optional,this.addTkObj.note).then(res=>{
        if(res.error_code==0){
          this.addTkObj.id=res.question_id;
          console.log(this.addTkObj.id);
          this.ReqAddToNair(res.question_id);
        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
      return -1;
    },
    addRate:function (){
      if(this.isAdding){
        this.SaveAddition();
      }
      this.isAdding=true;
      this.addType='rate';
      this.addRateObj.isEditing=true;
      this.addRateObj.title='评分题标题';
      this.addRateObj.note='';
      this.addRateObj.val=0;

      var optional=!this.addRateObj.bidati;
      questionCreateNonSelection(this.$store.state.uid,this.addRateObj.title,'R',optional,this.addRateObj.note).then(res=>{
        if(res.error_code==0){
          this.addRateObj.id=res.question_id;
          console.log(this.addRateObj.id);
          this.ReqAddToNair(res.question_id);
        }else{
          console.log(res);
        }
      }).catch(e=>{
        console.log(e);
      })
      return -1;
    },
    Save:function (item){
      //修改题干
      questionEditTitle(this.$store.state.uid,item.id,item.title).then(res=>{
        if(res.error_code==0){
          console.log("title修改成功");
        }else{
          console.log(res);
          return false;
        }
      }).catch(e=>{console.log(e);})

      //修改题干备注
      questionEditRemark(this.$store.state.uid,item.id,item.note).then(res=>{
        if(res.error_code==0){
          console.log("remark修改成功");
        }else{
          console.log(res);
          return false;
        }
      }).catch(e=>{console.log(e);})

      //修改必答与否
      var optional=!item.bidati;
      questionEditOptional(this.$store.state.uid,item.id,optional).then(res=>{
        if(res.error_code==0){
          console.log("optional修改成功");
        }else{
          console.log(res);
          return false;
        }
      }).catch(e=>{console.log(e);})

      //修改选项
      if(item.type=='dan'||item.type=='mul'){
        for(var i in item.options){
          if(!item.options[i].notEditing){
            this.ReqEditItemOptionDesc(item.options[i]);
            this.ReqEditItemOptionRemark(item.options[i]);
          }
        }
      }

     return true;
    },
    SaveAddition:function (){
      switch (this.addType){
        case 'dan':this.saveDan();break;
        case 'mul':this.saveMul();break;
        case 'tk':this.saveTk();break;
        case 'rate':this.saveRate();break;
      }
      this.isAdding=false;
      this.bidati=false;
      this.addType=null;
    },
    saveDan:function (){
      var savesuc=this.Save(this.addDanObj);
      if(savesuc){
        var q={};
        q.id=this.addDanObj.id;
        q.isEditing=false;
        q.title=this.addDanObj.title;
        q.note=this.addDanObj.note;
        q.type=this.addDanObj.type;
        q.radio=this.addDanObj.radio;
        q.bidati=this.addDanObj.bidati;
        var qops=[];
        for(var i in this.addDanObj.options){
          var vv={};
          vv.val=this.addDanObj.options[i].val;
          vv.remark=this.addDanObj.options[i].remark;
          vv.id=this.addDanObj.options[i].id;
          vv.notEditing=true;
          qops.push(vv);
        }
        q.options=qops;
        this.arr.push(q);
      }
    },
    saveMul:function (){
      var savesuc=this.Save(this.addMulObj);
      if(savesuc) {
        var q = {};
        q.id = this.addMulObj.id;
        q.isEditing = false;
        q.title = this.addMulObj.title;
        q.note = this.addMulObj.note;
        q.type = this.addMulObj.type;
        q.bidati = this.addMulObj.bidati;
        var qops = [];
        for (var i in this.addMulObj.options) {
          var vv = {};
          vv.val = this.addMulObj.options[i].val;
          vv.remark = this.addMulObj.options[i].remark;
          vv.id=this.addMulObj.options[i].id;
          vv.notEditing = true;
          qops.push(vv);
        }
        q.options = qops;
        var qches = [];
        for (var j in this.addMulObj.checked) {
          var oo = this.addMulObj.checked[j];
          qches.push(oo);
        }
        console.log(qches);
        q.checked = qches;

        this.arr.push(q);
      }
    },
    saveTk:function (){
      var savesuc=this.Save(this.addTkObj);
      if(savesuc) {
        var q = {};
        q.id = this.addTkObj.id;
        q.isEditing = false;
        q.title = this.addTkObj.title;
        q.note = this.addTkObj.note;
        q.type = this.addTkObj.type;
        q.text = this.addTkObj.text;
        q.bidati = this.addTkObj.bidati;
        this.arr.push(q);
      }
    },
    saveRate:function (){
      var savesuc=this.Save(this.addRateObj);
      if(savesuc) {
        var q = {};
        q.id = this.addRateObj.id;
        q.isEditing = false;
        q.title = this.addRateObj.title;
        q.note = this.addRateObj.note;
        q.type = this.addRateObj.type;
        q.text = this.addRateObj.val;
        q.bidati = this.addRateObj.bidati;
        this.arr.push(q);
      }
    },
    notSave:function (){
      switch (this.addType){
        case 'dan':this.ReqDelete(this.addDanObj);break;
        case 'mul':this.ReqDelete(this.addMulObj);break;
        case 'tk':this.ReqDelete(this.addTkObj);break;
        case 'rate':this.ReqDelete(this.addRateObj);break;
      }
      this.isAdding=false;
      this.addType=null;
      this.bidati=false;
    },
  }
}
</script>

<style scoped>
body,span{
  line-hight:1.5;
}
/deep/ .el-card__body {
  padding: 0px;
}
/deep/ .el-form-item {
  background-color: unset !important;
}
/deep/ .el-radio__label{
  line-hight:1.5;
  word-break: break-all;
  white-space: normal;
  word-wrap:break-word;
}

</style>